package com.hmkj.admin.controller.operate;

import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.po.operate.PointRule;
import com.hmkj.core.service.operate.PointRuleService;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping(BaseController.BASE_URI)
public class PointRuleJsonController extends GenericController {

    @Resource
    private PointRuleService pointRuleService;

    /**
     * 积分规则列表json数据
     */
    @ResponseBody
    @RequestMapping(value = "pointRule/json/list", method = RequestMethod.POST)
    @RequiresPermissions("sys:point:rule:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        return pointRuleService.getDtGridList(dtGridPager, PointRule.class);
    }


    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping(value = "/pointRule/json/edit")
    @RequiresPermissions("sys:point:rule:edit")
    public ResultEntity edit(PointRule pointRule) throws Exception {
        //参数校验
        checkModel(pointRule,"update");
        pointRuleService.doEdit(pointRule);
        return ok();
    }

    /**
     * 修改状态
     */
    @ResponseBody
    @RequestMapping(value = "/pointRule/json/state")
    @RequiresPermissions("sys:point:rule:state")
    public ResultEntity state(Integer id, Integer status) throws Exception {
        //参数校验
        if(null == id || null == status){
            throw new BussinessException("参数错误");
        }
        if(status != PointRule.STATUS.T1.code && status != PointRule.STATUS.T2.code){
            throw new BussinessException("状态参数错误");
        }
        PointRule pointRule = pointRuleService.selectOne(new PointRule(c -> c.setId(id)));
        if(null ==pointRule){
            throw new BussinessException("该积分规则不存在");
        }
        pointRule.setStatus(status);
        pointRuleService.updateByIdAndVersionSelective(pointRule);
        return ok();
    }

    /**
     * model校验
     * @return
     */
    void checkModel(PointRule model,String type){
        //编辑需要校验Id
        if("update".equals(type)){
            if(null == model.getId()){
                throw new BussinessException("参数有误");
            }
        }
        if(StrUtil.isBlank(model.getTitle())){
            throw new BussinessException( "请填写规则标题");
        }
        if(StrUtil.isBlank(model.getValue())){
            throw new BussinessException( "请填写规则参数");
        }
    }

}